module framework.Events;
import framework.JobHub;
import derelict.sdl.sdl;
import std.c.stdlib;
import std.stdio;

EventPooler _eventPooler;

static this (){
	_eventPooler=new EventPooler();
}

EventPooler eventPooler(){
	return _eventPooler;
}

class EventPooler{
	private void delegate (SDL_MouseMotionEvent)[] mouseMotions;
	private void delegate (SDL_MouseButtonEvent)[] mouseClicked;
	private void delegate (SDL_KeyboardEvent)[] keypressed;

	this(){
		jobHub.register(&this.update);
	}

	void register(void delegate (SDL_MouseMotionEvent) d){
		mouseMotions~=d;
	}

	void register(void delegate (SDL_MouseButtonEvent) d){
		mouseClicked~=d;
	}
	
	void register(void delegate (SDL_KeyboardEvent) d){
		keypressed~=d;
	}

	void update(){
		char* sdl_error;
		sdl_error = SDL_GetError( );									
		if( sdl_error[0] != 0 ) {
				printf("SDL error '%s'\n", sdl_error);	
				SDL_ClearError();											
			}
		SDL_Event event;
		while (SDL_PollEvent(&event)) {
			switch(event.type){
				case SDL_MOUSEMOTION: foreach(m;mouseMotions) m(event.motion); break;
			    case SDL_MOUSEBUTTONDOWN: foreach(m; mouseClicked) m(event.button);  break;
				case SDL_KEYDOWN: foreach(k; keypressed) k(event.key); break;
				case SDL_KEYUP: foreach(k; keypressed) k(event.key); break;
				case SDL_QUIT: exit(0);
				default: break;
			}
		}
	}
}